/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 添加修改广告
 *  */
import React, { useMemo, useCallback, useRef } from "react";
import PropTypes from "prop-types";
import { connect } from "dva";
import { Button, Col, Row, Switch, Table, Popconfirm, Typography } from "antd";
import KbPreviewImage from "@/components/KbPreviewImage";
import { DndProvider, useDrag, useDrop } from "react-dnd";
import { HTML5Backend } from "react-dnd-html5-backend";
import update from "immutability-helper";
import "./AdvTable.less";

const { Paragraph } = Typography;

const TYPE = "DraggableBodyRow";

const DraggableBodyRow = ({ index, moveRow, className, style, ...restProps }) => {
  const ref = useRef();
  const [{ isOver, dropClassName }, drop] = useDrop({
    accept: TYPE,
    collect: monitor => {
      const { index: dragIndex } = monitor.getItem() || {};
      if (dragIndex === index) {
        return {};
      }
      return {
        isOver: monitor.isOver(),
        dropClassName: dragIndex < index ? " drop-over-downward" : " drop-over-upward",
      };
    },
    drop: item => {
      moveRow(item.index, index);
    },
  });
  const [, drag] = useDrag({
    type: TYPE,
    item: { index },
    collect: monitor => ({
      isDragging: monitor.isDragging(),
    }),
  });
  drop(drag(ref));

  return (
    <tr
      ref={ref}
      className={`${className}${isOver ? dropClassName : ""}`}
      style={{ cursor: "move", ...style }}
      {...restProps}
    />
  );
};

const components = {
  body: {
    row: DraggableBodyRow,
  },
};

const AdvTable = ({ advList, loading, onEditAdv, dispatch, getList }) => {
  const onDelete = useCallback(
    id => {
      dispatch({
        type: "wxSettings/deleteAdv",
        payload: {
          id,
        },
      }).then(() => {
        getList();
      });
    },
    [dispatch, getList]
  );

  const onStatusChange = useCallback(
    (status, id) => {
      dispatch({
        type: "wxSettings/changeAdvStatus",
        payload: {
          id,
          status: status ? 1 : 2,
        },
      }).then(() => {
        getList();
      });
    },
    [dispatch, getList]
  );

  const columns = useMemo(
    () => [
      {
        title: "排序",
        dataIndex: "sort",
        width: 100,
        key: "sort",
        align: "center",
      },
      {
        title: "广告图",
        dataIndex: "image_url",
        key: "image_url",
        width: 150,
        render: image_url => <KbPreviewImage src={image_url} />,
      },
      {
        title: "跳转链接",
        dataIndex: "advertising_url",
        key: "advertising_url",
        width: 600,
        render: text => <Paragraph ellipsis={{ rows: 3, expandable: true }}>{text}</Paragraph>,
      },
      {
        title: "操作",
        width: 300,
        align: "center",
        render: (_, record) => {
          const { id, status } = record;
          const disabled = status == "1"; // 已上线无法编辑删除
          return (
            <Row type="flex" justify="space-between" align="middle">
              <Col>
                <Button disabled={disabled} type="primary" onClick={() => onEditAdv(record)}>
                  编辑
                </Button>
              </Col>
              <Col>
                <Switch
                  onChange={e => onStatusChange(e, id)}
                  defaultChecked={disabled}
                  checkedChildren="下线"
                  unCheckedChildren="上线"
                />
              </Col>
              <Col>
                <Popconfirm
                  disabled={disabled}
                  title="确认删除该广告？"
                  onConfirm={() => onDelete(id)}
                >
                  <Button disabled={disabled} type="danger">
                    删除
                  </Button>
                </Popconfirm>
              </Col>
            </Row>
          );
        },
      },
    ],
    [onEditAdv, onDelete, onStatusChange]
  );

  const moveRow = useCallback(
    (dragIndex, hoverIndex) => {
      const dragRow = advList[dragIndex];
      dispatch({
        type: "wxSettings/save",
        payload: {
          advList: update(advList, {
            $splice: [[dragIndex, 1], [hoverIndex, 0, dragRow]],
          }),
        },
      });
      dispatch({
        type: "wxSettings/sortAdv",
      }).then(() => {
        getList();
      });
    },
    [advList, dispatch, getList]
  );

  return (
    <DndProvider backend={HTML5Backend}>
      <Table
        rowKey="id"
        loading={loading}
        dataSource={advList}
        columns={columns}
        pagination={false}
        components={components}
        scroll={{ x: 1200 }}
        onRow={(_, index) => ({
          index,
          moveRow,
        })}
      />
    </DndProvider>
  );
};

AdvTable.propTypes = {
  onEditAdv: PropTypes.func.isRequired, // 打开广告设置弹窗，并回传广告数据
  getList: PropTypes.func.isRequired,
};

export default connect(({ loading, wxSettings }) => ({
  advList: wxSettings.advList,
  loading: loading.effects["wxSettings/getAdvList"],
}))(React.memo(AdvTable));
